package controller

import (
	"github.com/duke-git/lancet/v2/validator"
	"github.com/gin-gonic/gin"
	"shorten/internal/service"
	"shorten/pkg/app"
	"shorten/pkg/errcode"
)

// 生成一个短地址
func (b *base) GenOne(c *gin.Context) {
	//1 参数基础校验
	var param service.ShortenGenParam
	code, msg := service.BindAndValid(c, &param)
	if code > 0 {
		app.FailedWithMsg(c, code, msg)
		return
	}
	userId := b.UserID(c)
	//2 生成对应短地址
	svc := service.New(c.Request.Context())
	sign, err := svc.GenSign(userId, param.Url)
	if err != nil {
		app.Failed(c, errcode.SHORTEN_GEN_FAIL)
		return
	}
	//3 返回对应信息
	app.Success(c, gin.H{
		"sign": sign,
	})
}

// 获取一个短地址
func (b *base) GetOne(c *gin.Context) {
	//1 获取短地址签名+基础校验
	sign := c.Param("sign")
	checked := validator.IsAlpha(sign)
	if !checked {
		//app.Failed(c, errcode.InvalidParams)
		//return
	}
	//2 获取短地址对应的原地址
	svc := service.New(c.Request.Context())
	url, err := svc.GetUrlBySign(c, sign)
	if err != nil {
		app.FailedWithMsg(c, errcode.SHORTEN_GET_FAIL, err.Error())
		return
	}
	//3 返回信息
	app.Success(c, gin.H{
		"sign": sign,
		"url":  url,
	})
}

// 短地址使用排行榜
func (b *base) Rank(c *gin.Context) {

}
